package controller;


import context.SpringContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import pojo.User;
import service.UserService;

import java.util.UUID;

@Controller
public class UserController {

    //private UserService userService = ServiceFactory.getUserServiceInstance();

    private UserService userService;

    public UserController(){
//        userService = (UserService) SpringContext.getInstance().getContext().getBean("userServiceCH");
        userService = (UserService) SpringContext.getInstance().getContext().getBean("userServiceDB");
    }

    @RequestMapping(value = "/addUser",method = RequestMethod.POST)
    public String add(User user){
        user.setId(UUID.randomUUID().toString());
        userService.add(user);
        return "redirect:user/all";
    }

    @RequestMapping("/user/all")
    public String get(Model model) {
        model.addAttribute("users", userService.getAllUser());
        System.out.println(userService.getAllUser());
        return "list";

    }

    @RequestMapping(value = "user/all/asyn",method = RequestMethod.GET)
    @ResponseBody
    public Object getUsers(){
        return  userService.getAllUser();
    }

    @RequestMapping(value = "user/add/asyn",method = RequestMethod.POST)
    @ResponseBody
    public Object addUser(@RequestBody User user){
        user.setId(UUID.randomUUID().toString());
        System.out.println(user);
        return userService.add(user);
    }

    @RequestMapping(value = "user/update/asyn",method = RequestMethod.PUT)
    @ResponseBody
    public Object updateUser(@RequestBody User user){
        return userService.update(user);
    }

    @RequestMapping(value = "user/delete/{uid}",method = RequestMethod.DELETE)
    @ResponseBody
    public Object deleteUser(@PathVariable("uid") String uid){
        User user =  userService.delete(uid);
       return user;

    }


}
